package bb.lanxing.activity.discover;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.mylhyl.circledialog.CircleDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.activity.team.ImageEditActivity;
import bb.lanxing.adapter.discover.BbsImageCreateAdapter;
import bb.lanxing.model.database.Bbs;
import bb.lanxing.model.database.BbsType;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.network.NetSubscribe;
import bb.lanxing.util.CommonUtil;
import bb.lanxing.util.image.GlideEngine;
import okhttp3.Request;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class BbsCreateActivity extends BaseActivity {
    private TextView typeName;
    private BbsImageCreateAdapter bbsImageAdapter = new BbsImageCreateAdapter();
    private ArrayList<String> imageList = new ArrayList<>();

    private Bbs bbs = new Bbs();
    private ArrayList<BbsType> bbsTypesList = new ArrayList<>();
    private String[] bbsTypesName;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bbs_create);

        ImageView back = findViewById(R.id.back);
        back.setOnClickListener(v -> onBackPressed());

        LinearLayout typeLayout = findViewById(R.id.typeLayout);
        typeLayout.setOnClickListener(v -> {
            new CircleDialog.Builder().setItems(bbsTypesName, (parent, view, position, id) -> {
                        ArrayList<Integer> typeList = new ArrayList<>();
                        typeList.add(bbsTypesList.get(position).typeId);
                        bbs.typeList = typeList;
                        typeName.setText(bbsTypesName[position]);
                        return true;
                    }
            ).show(getSupportFragmentManager());
        });
        typeName = findViewById(R.id.typeName);

        EditText content = findViewById(R.id.content);
        content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                bbs.content = s.toString();
            }
        });

        RecyclerView imageRecyclerView = findViewById(R.id.imageRecyclerView);
        imageRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        bbsImageAdapter.updateData(imageList);
        bbsImageAdapter.setOnItemClickListener(position -> {
            if (BbsImageCreateAdapter.TYPE_ADD == bbsImageAdapter.getItemViewType(position)) {
                int newNum = 9 - imageList.size();
                PictureSelector.create(this).openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine()).setMaxSelectNum(newNum)
                        .forResult(new OnResultCallbackListener<>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result) {
                                for (LocalMedia localMedia : result) {
                                    imageList.add(localMedia.getRealPath());
                                }
                                bbs.imageList = imageList;
                                bbsImageAdapter.updateData(imageList);
                            }

                            @Override
                            public void onCancel() {
                            }
                        });
            } else {
                Intent intent = new Intent(this, ImageEditActivity.class);
                intent.putStringArrayListExtra("images", imageList);
                intent.putExtra("currentImage", position);
                startActivityForResult(intent, 23);
            }
        });
        imageRecyclerView.setAdapter(bbsImageAdapter);

        TextView commitBtn = findViewById(R.id.commitBtn);
        commitBtn.setOnClickListener(v -> onCommitClick());

        loadData();
    }

    private void loadData() {
        BiCiCallback biCiCallback = new BiCiCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
            }

            @Override
            public void onResponseString(@NonNull String string) {
                System.out.println("string1: " + string);
                if (!TextUtils.isEmpty(string)) {
                    try {
                        JSONObject jsonObject = new JSONObject(string);
                        int code = jsonObject.optInt("code");
                        if (200 == code) {
                            try {
                                JSONArray jSONArray = new JSONObject(string).getJSONArray("rows");
                                bbsTypesList.add(new BbsType("全部", 0));
                                bbsTypesName = new String[jSONArray.length() + 1];
                                bbsTypesName[0] = "全部";
                                for (int i = 0; i < jSONArray.length(); i++) {
                                    BbsType createByJson = BbsType.createByJson(jSONArray.getJSONObject(i));
                                    bbsTypesList.add(createByJson);
                                    bbsTypesName[i + 1] = createByJson.typeName;
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            runOnUiThread(() -> {

                            });
                        }
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    toast("获取类型列表失败");
                }
            }
        };
        MyHttpClient.getForumTypeList(biCiCallback);
    }

    private void onCommitClick() {
        if (validDatas(true)) {
            postBbs();
        }
    }

    private boolean validDatas(boolean showToast) {
        if (TextUtils.isEmpty(bbs.content) && (bbs.imageList == null || bbs.imageList.size() == 0)) {
            if (showToast) {
                App.getContext().showMessage("文字或者图片，不能都是空哦");
            }
            return false;
        } else {
            return true;
        }
    }

    private void postBbs() {
        showLoadingDialog("正在发布帖子...", true, null);
        if (TextUtils.isEmpty(bbs.content)) {
            bbs.content = " ";
        }
        Observable.create(new NetSubscribe(MyHttpClient.createBbs(bbs))).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
                    @Override
                    public void onCompleted() {
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onError(Throwable th) {
                        toast("发帖失败");
                        dismissLoadingDialog();
                    }

                    @Override
                    public void onNext(String str) {
                        if (!TextUtils.isEmpty(str)) {
                            try {
                                JSONObject jsonObject = new JSONObject(str);
                                int code = jsonObject.optInt("code");
                                if (200 == code) {
                                    toast("发帖成功");
                                    bbs.serverId = jsonObject.optInt("data");
                                    if (bbs.imageList != null && imageList.size() > 0) {
                                        postBbsImage();
                                    } else {
                                        finish();
                                    }
                                }
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        } else {
                            toast("发帖失败");
                        }
                    }
                });
    }

    private void postBbsImage() {
        updateImages(bbs.imageList).flatMap((Func1<String, Observable<String>>) s -> {
            List<Long> imageServerIdlist = new ArrayList<>();
            String[] args = s.split(";");
            try {
                for (int i = 0; args != null && i < args.length; i++) {
                    JSONObject jsonObject = new JSONObject(args[i].toString());
                    int code = jsonObject.getInt("code");
                    if (200 == code) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        long fileId = jsonObject1.getLong("fileId");
                        imageServerIdlist.add(fileId);
                    }
                }
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            return Observable.create(new NetSubscribe(MyHttpClient.attachBbsPic(bbs.serverId, imageServerIdlist)));
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                toast("帖子图片绑定失败");
                dismissLoadingDialog();
            }

            @Override
            public void onNext(String s) {
                if (!TextUtils.isEmpty(s)) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        int code = jsonObject.optInt("code");
                        if (200 == code) {
                            toast("帖子图片绑定成功");
                        }
                    } catch (JSONException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    toast("帖子图片绑定失败");
                }
                finish();
                dismissLoadingDialog();
            }
        });
    }

    private Observable<String> updateImages(List<String> images) {
        if (images == null || images.isEmpty()) {
            return Observable.just("");
        }
        return Observable.just(images).flatMap((Func1<List<String>, Observable<String>>) images2 -> {
            if (images2 == null || images2.isEmpty()) {
                return Observable.just(null);
            }
            ArrayList arrayList = new ArrayList();
            for (String image : images2) {
                if (!image.startsWith("http://") && !image.startsWith("https://")) {
                    arrayList.add(updateImage(image));
                }
            }
            return Observable.zip(arrayList, args -> {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; args != null && i < args.length; i++) {
                    sb.append(args[i].toString());
                    if (i < args.length - 1) {
                        sb.append(";");
                    }
                }
                return sb.toString();
            });
        });
    }

    private Observable<String> updateImage(String fileName) {
        String md5 = CommonUtil.getMD5(new File(fileName));
        return Observable.create(new NetSubscribe(MyHttpClient.uploadBbsPic(fileName, md5, null)));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_OK) {
            imageList = data.getStringArrayListExtra("images");
            bbs.imageList = imageList;
            bbsImageAdapter.updateData(imageList);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}